<template>
  <div class="rich-text-editor">
    <div ref="editorRef" class="editor-container" :style="{ height: height + 'px' }"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, defineProps, defineEmits } from 'vue'
import { createEditor, createToolbar } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
import request from '@/api/request'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: Number,
    default: 300
  }
})

const emit = defineEmits(['update:modelValue'])

const editorRef = ref()
let editor: any = null
let toolbar: any = null

// 自定义上传图片函数
const customUpload = async (file: File, insertFn: any) => {
  try {
    const formData = new FormData()
    formData.append('image', file)
    
    // 使用我们自定义的request实例，它会自动添加认证头
    const response = await request.post('/health/upload/image/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    // 插入图片到编辑器
    insertFn(response.data.url || '', '', '')
  } catch (error: any) {
    console.error('图片上传失败:', error)
    ElMessage.error(error.message || '图片上传失败')
  }
}

// 工具栏配置
const toolbarConfig: any = {}

// 编辑器配置
const editorConfig: any = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      // 使用自定义上传
      customUpload: customUpload,
      fieldName: 'image',
      maxFileSize: 5 * 1024 * 1024, // 5MB
      base64LimitSize: 5 * 1024, // 5KB以下插入base64
      onSuccess(file: any, res: any) {
        console.log('上传成功', file, res)
      },
      onError(file: any, err: any, res: any) {
        console.log('上传失败', file, err, res)
      }
    }
  }
}

// 初始化编辑器
const initEditor = () => {
  if (!editorRef.value) return

  // 创建编辑器
  editor = createEditor({
    selector: editorRef.value,
    config: editorConfig,
    html: props.modelValue,
    mode: 'default'
  })

  // 创建工具栏
  const toolbarRef = document.createElement('div')
  toolbarRef.className = 'editor-toolbar'
  editorRef.value.parentNode.insertBefore(toolbarRef, editorRef.value)
  toolbar = createToolbar({
    editor,
    selector: toolbarRef,
    config: toolbarConfig,
    mode: 'default'
  })

  // 监听内容变化
  editor.on('change', () => {
    const content = editor.getHtml()
    emit('update:modelValue', content)
  })
}

// 清理编辑器
const destroyEditor = () => {
  if (editor) {
    editor.destroy()
    editor = null
  }
  if (toolbar) {
    toolbar.destroy()
    toolbar = null
  }
}

// 监听值变化
watch(() => props.modelValue, (newVal) => {
  if (editor && newVal !== editor.getHtml?.()) {
    editor.setHtml?.(newVal)
  }
})

onMounted(() => {
  initEditor()
})

onBeforeUnmount(() => {
  destroyEditor()
})
</script>

<style scoped>
.editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}
</style>